package model
{
	import mx.collections.ArrayCollection;
	
	[Bindable]
	public class Page
	{
		public static const HOME_PAGE: String = "home";
		
		public function Page(pageId:String=null) {
			_pageId = pageId;
			_history = new ArrayCollection();
		}
		
		public function addUpdate(pu: PageUpdate): void {
			if (_history.length>0) {
				var lastUpdate: PageUpdate = _history.getItemAt(_history.length-1) as PageUpdate;
				if (lastUpdate.pageId == pu.pageId) {
					_history.addItem(pu);
				}
			}
			else {
				_pageId = pu.pageId;
				_history.addItem(pu);
			}
		}
		
		public function addUpdates(updates: ArrayCollection): void {
			if (updates != null) {
				for (var i:int = 0; i<updates.length; i++) {
					addUpdate(updates.getItemAt(i) as PageUpdate);
				}
			}
		}
		
		public function get pageId(): String {
			return _pageId;
		}
		
		public function get text(): String {
			if (!isNew()) {
				var pu: PageUpdate = _history.getItemAt(_history.length-1) as PageUpdate;
				return pu.diffText;
			}
			else {
				return "";
			}
		}
		
		public function get lastModificationDate(): Date {
			if (!isNew()) {
				var pu: PageUpdate = _history.getItemAt(_history.length-1) as PageUpdate;
				return pu.modificationDate;
			}
			else {
				return null;
			}
		}
		
		public function get history(): ArrayCollection {
			return _history;
		}
		
		public function get label(): String {
			return _pageId;
		}
		
		public function isNew(): Boolean {
			return (_history==null || _history.length == 0);
		}
		
		public function toString(): String {
			var result: String = "Page[";
			result += "pageId: '" + pageId + "'";
			result += ", lastModificationDate: '" + lastModificationDate + "'";
			result += ", version: '" + isNew() ? "new" : _history.length+1 + "'";
			//result += ", text: '" + text + "'";
			result += "]";
			return result;
		}
		
		private var _pageId: String = null;
		private var _history: ArrayCollection; // a collection of PageUpdates
	}
}